<?php

	if (!isset($sAPP) || !is_string($sAPP) || !isset($aSUITE) || !is_array($aSUITE) || !isset($aSUITE[$sAPP])) {

	   	/**
		 * Intercetto la situazione in cui viene eseguito direttamente questo script (ovvero quando
		 * questo script non e' incluso in $sapp/index.php
		 *
		 */

		header('Location: ../index.php'); die();
	} 
	
	fnGetValueFromGET();
	
	$sScript = fnCurrentScript();
	$sSCRIPT_ROOT_PATH = (fnIsScriptInRoot() ? '.' : '..'); // Variabile utilizzata in template.php
	
	if(!isset($sType) || !isset($aRESOURCES[$sType]) || !in_array($sType, $aRESOURCES_APP)) {
		die('ERROR: sType not defined');
	}
	
	$iAccessLvl = fnGetAccessLvl('app');

	$bSEARCH_FORM_SHOW = false;
	$sParentData = '{ }';
	$sJQueryValidateRule = '';

	if ($aRESOURCES[$sType]['sParentType'] != '') {
		
		
		if ((!isset($sAction) || $sAction=='view') & !$aRESOURCES[$sType]['bParentMandatory']) {
			// pagina 'elenco risorse', con campo iParent non obbligatorio
			$aParentData = array('' => 'Nessuna selezione');
		} else if ((!isset($sAction) || $sAction=='view') & $aRESOURCES[$sType]['bParentMandatory']) {
		 	// pagina 'elenco risorse', con campo iParent obbligatorio
		 	$aParentData = array();
		} else if (isset($sAction) && $sAction=='new') {
			// pagina 'aggiungi risorsa'
			$aParentData = array('' => 'Seleziona '.$aRESOURCES[$aRESOURCES[$sType]['sParentType']]['sLabelSingleItem'].'...');
		}
		
		if ($aRESOURCES[$sType]['bParentMandatory']) {
			// se il campo iParent è obbligatorio utilizzo 'jquery.validate()'
			$sJQueryValidateRule = ", iParent: { required: true }";
		}
		
		$sQuery = fnGetResourcesQuery($aRESOURCES[$sType]['sParentType']);
		$rResult = custom_mysql_query($sQuery, 'fnGetResourcesQuery()');
		if (mysql_num_rows($rResult) > 0) {
			while ($aRow = mysql_fetch_assoc($rResult)) {
				$aParentData[$aRow['id']] = $aRow['sDescription'];	
			}
		}
		
		$sParentData = json_encode($aParentData);
		
	}

	$sMessageFlash = fnMessageFlash();
	
	if (isset($sAction)) {

		switch ($sAction) {
			
			case 'new':
			
				//
				// CODICE HTML PAGINA "AGGIUNGI RISORSA"
				//
			
				if (is_allowed('edit', $iAccessLvl)) {				
				
					$sLEFT_NAV_IMG = "accessories-text-editor.png";
					$sHeaderTitle = $sTableTitle = "Gestione Risorse &raquo; Aggiungi ".$aRESOURCES[$sType]['sLabelSingleItem'];
					
					$sHeadContent = "
						<script type='text/javascript' src='../include/jquery.validate.min.js'></script>
						<script type='text/javascript' src='../include/messages_it.js'></script>
						<script type='text/javascript' src='../include/methods_it.js'></script>
						<script type='text/javascript'>
							
							$().ready(function() {
								
								$('button').button();
								
								$('#resources-new').validate({
									rules: {
										sDescription: { required: true }
										$sJQueryValidateRule
									}
								});
												
							});
						</script>";
					
					$html .= "<a href='./resources.php?sType=$sType'>&laquo; Ritorna a Gestione Risorse &raquo; ".$aRESOURCES[$sType]['sLabelSingleItem']."</a>";
					
					$html .= "<form id='resources-new' method='get' action='./resources.php'>";
	
					$html .= "<input type='hidden' name='sAction' value='add'>";
					$html .= "<input type='hidden' name='sType' value='$sType'>";
					
						$html .= "<table><tbody>";
						
						$html .= "<tr>
									<th>Descrizione</th>
									<td>
										<input type='text' id='sDescription' name='sDescription'>
									</td></tr>";
						
						foreach ($aRESOURCES[$sType]['aFields'] as $sField) {
							
							if ($sField == 'iParent') {
								$html .= "<tr>
											<th>".$aRESOURCES[$aRESOURCES[$sType]['sParentType']]['sLabelSingleItem']."</th>
											<td>
												<select id='$sField' name='$sField'>";
								
								foreach ($aParentData as $iParent => $sLabel) {
									$html .= "		<option value='$iParent'>$sLabel</option>";	
								}
								
								$html .= "		</select>";
								$html .= "	</td></tr>";
								
							} else {
								$html .= "<tr>
											<th>$sField</th>
											<td>
												<input type='text' name='$sField'>
											</td></tr>";
							} 
				
						}
				
						$html .= "<tr>
									<th>&nbsp;</th>
									<td>
									<button id='submit' type='submit'>Salva</button>
									</td></tr>";
									
						$html .= "</tbody></table>";
	
					$html .= "</form>";
													
				} else  {
					fnUpdateLog('LOW RIGHTS ['.$sScript.']', 0, '', '','S');			
					header("Location: ./resources.php?sType=$sType&sMsg=low-rights");
					
				}	
				
				break;
				
			case 'add':
			
				//
				// CODICE MYSQL: INSERT INTO `resources` ...
				//
			
				if (is_allowed('edit', $iAccessLvl)) {	
				
					$sQuery = "INSERT INTO `resources` (id, sDescription, sType, iShow) VALUES (NULL, '$sDescription', '$sType', 1)";
					$rResult = custom_mysql_query($sQuery);	
					$iResource = mysql_insert_id($rConn);
					
					if (isset($aRESOURCES[$sType]['aFields']) && !empty($aRESOURCES[$sType]['aFields'])) {
						$bQuery = false;
						$sQuery = "INSERT INTO `properties` (`sSelectFrom`, `iTable`, `sField`, `sValue`) VALUES ";
						foreach ($aRESOURCES[$sType]['aFields'] as $sField) {
							$sValue = $$sField;
							if ($sValue != '') {
								$bQuery = ($bQuery ? $bQuery : true);
								$sQuery .= "('resources', $iResource, '$sField', '$sValue'), ";
							}
						}
						if ($bQuery) {
							// eseguo questa query solo se almeno un campo non è vuoto!
							$rResult = custom_mysql_query(substr($sQuery, 0, -2));
						}
					}
					
					fnUpdateLog('NEW RESOURCE ['.$sType.']', 0, 'resources','I');	
					header("Location: ./resources.php?sType=$sType&iResourceNew=$iResource");
					die();
				
				} else  {
					fnUpdateLog('LOW RIGHTS', 0, 'resources','S');	
					header("Location: ./resources.php?sType=$sType&sMsg=low-rights");
					
				}	
				
				break;
				
			default:

				//
				// CODICE HTML PAGINA "VISUALIZZA ELENCO RISORSE"
				//
				
				$sLEFT_NAV_IMG = "accessories-text-editor.png";
				$sHeaderTitle = $sTableTitle = "Gestione Risorse &raquo; ".$aRESOURCES[$sType]['sLabel'];
				$sNewItem = "<a href='./resources.php?sType=$sType&sAction=new'>Aggiungi ".$aRESOURCES[$sType]['sLabelSingleItem']." &raquo;</a>";
				
				$sHeadContent = "
				
					<script type='text/javascript' src='../include/dataTables/media/js/jquery.dataTables.js'></script>
					<script type='text/javascript' src='../include/jquery.jeditable.mini.js'></script>
					
					<link type='text/css' href='../include/dataTables/media/css/demo_table.css' rel='stylesheet' />
					
			
					<script type='text/javascript' charset='utf-8'>
			
						var oTable;
						
						function fnToggleShowResource (oObj) {
							src = oObj.attr('src') ,
							onCheck = /\_on\.png$/ ,
							offCheck = /\_off\.png$/ ;
							
							$.getJSON('../include/resources.toggle.php', {'sAPP': '$sAPP', 'sType': '$sType', 'iResource': oObj.parents('tr:first').attr('iResource'), 'sAction': 'toggle', 'sField': oObj.attr('sField'), 'sValue': (src.match(onCheck) ? 0 : 1) }, function (json) {
								if (json[0].sAction=='toggle' && json[0].sError=='') { 
									if(src.match(onCheck)) {
										oObj.attr('src', src.replace(onCheck, '_off.png'));
										oObj.parent().next().addClass('strike-through');
										
									} else if (src.match(offCheck)) {
										oObj.attr('src', src.replace(offCheck, '_on.png'));
										oObj.parent().next().removeClass('strike-through');

									}
								} else { 
									alert ('Error: ' + json[0].sError);
								} 		
							})
							
						} ";
					
				$sHeadContent .= "
				
						$(document).ready(function() {
						
							setTimeout(function(){ $('.ui-message-flash').fadeOut(); }, 1800);							
							
							/* Init DataTables */
							oTable = $('#resources').dataTable({
								'sDom': \"<'dt_filter'f>rt<'dt_info'ip><'dt_length'l>\",
								'oLanguage': { 'sUrl': '../include/dataTables/it_IT.txt' },		
								'bAutoWidth': false,
								'iDisplayLength': 30,
								'aoColumnDefs': [ { 'sWidth': '20px', 'bSortable': false, 'aTargets': [ 0 ] } ]
							}); ";

				if (is_allowed('edit', $iAccessLvl)) {							
					
					$sHeadContent .= "
				
							$('.toggable').click(function() {
								fnToggleShowResource($(this));
							});	

							
							/* Apply the jEditable handlers to the table */
							$('.editable', oTable.fnGetNodes()).editable( '../include/resources.jeditable.php', {
								cancel : 'Annulla',
								submit : 'Salva',
								tooltip : 'Clicca per modificare',
								placeholder : '&nbsp;',
								cssclass : 'jeditable',
								name : 'sValue',
								'callback': function(sValue, y) {
									var aPos = oTable.fnGetPosition(this);
									oTable.fnUpdate(sValue, aPos[0], aPos[1]);
								},
								'submitdata': function(value, settings) {
									return {
										'sAPP': '$sAPP',
										'sType': '$sType',
										'sField': this.getAttribute('sField'),
										'iResource': this.parentNode.getAttribute('iResource'),
										'column': oTable.fnGetPosition(this)[2]
									};
								}
							} );
			
							$('.editable_select', oTable.fnGetNodes()).editable( '../include/resources.jeditable.php', {
								type : 'select',
								data : $sParentData,
								submit : 'Salva',
								name : 'sValue',
								'callback': function(sValue, y) {
									var aPos = oTable.fnGetPosition(this);
									oTable.fnUpdate(sValue, aPos[0], aPos[1]);
								},
								'submitdata': function(value, settings) {
									return {
										'sAPP': '$sAPP',
										'sType': '$sType',
										'sField': this.getAttribute('sField'),
										'iResource': this.parentNode.getAttribute('iResource'),
										'column': oTable.fnGetPosition(this)[2]
									};
								}
							} ); ";
				
				}
				
				$sHeadContent .= "							
											
						});
						
					</script> ";


				$sQuery = fnGetResourcesQuery($sType, $aRESOURCES[$sType]['aFields']);
				$aData = fnGetDataFromQuery($sQuery, 'fnGetResourcesQuery()');
				
				$html .= "<div>&nbsp;</div>";
				
				$html .= "<table class='display' id='resources' cellspacing='0' cellpadding='0'>";
				$html .= "	<thead>";
				$html .= "		<tr>";
				
				$html .= "			<th>Visibile</th>";
				$html .= "			<th>Descrizione</th>";
					
				foreach ($aRESOURCES[$sType]['aFields'] as $sField) {
					if ($sField == 'iParent') {
						$html .= "	<th>".$aRESOURCES[$aRESOURCES[$sType]['sParentType']]['sLabelSingleItem']."</th>";
					} else {
						$html .= "	<th>$sField</th>";
					}
				}
				
				$html .= "		</tr>";
				$html .= "	</thead>";
				$html .= "	<tbody>";
						
				if (!empty($aData)) {
					
					foreach ($aData as $aRow) {
						$html .= "<tr iResource='".$aRow['id']."'>";
					
						$html .= "		<td class='center'><img class='toggable' sField='iShow' src='../themes/common/images/wcheck_".($aRow['iShow']==1 ? "on" : "off").".png'></td>";
						$html .= "		<td class='editable".($aRow['iShow']==1 ? '' : " strike-through")."' sField='sDescription'>".$aRow['sDescription']."</td>";
							
						foreach ($aRESOURCES[$sType]['aFields'] as $sField) {
							if ($sField == 'iParent') {
								$html .= "	<td class='editable_select' sField='iParent'>".fnGetParentDescription($aRow[$sField], $aParentData)."</td>";
							} else {
								$html .= "	<td class='editable' sField='$sField'>".$aRow[$sField]."</td>";
							} 
						}
							
						$html .= "</tr>";
						
					}
				}
				
				$html .= "	</tbody>";
				$html .= "</table>";
				
				break;		
		
		}
		
	}	
	
	require_once('../themes/'.$sTHEME.'/template.php');
	die();
	
?><html><body bgcolor="#fff"></body></html>
